package com.ktjy.config;

import com.ktjy.filter.JwtTokenFilter;
import com.ktjy.handler.MyAccessDeniedHandler;
import com.ktjy.handler.MyAuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
    @Autowired
    MyAccessDeniedHandler myAccessDeniedHandler;
    @Autowired
    MyAuthenticationEntryPoint myAuthenticationEntryPoint;
    @Autowired
    JwtTokenFilter jwtTokenFilter;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        //配置权限
        httpSecurity.authorizeHttpRequests(authz ->
                authz
                        .requestMatchers("/api/login").permitAll()///login接口所有人都能访问
                        .requestMatchers("/api/logout").permitAll()
                        .requestMatchers("/api/captcha").permitAll()
                        .requestMatchers("/ws/**").permitAll()  //ws请求放行
                        // 放开 Knife4j 相关路径
                        .requestMatchers(
                                "/doc.html",                    // Knife4j 文档首页
                                "/webjars/**",                  // Knife4j 依赖的 webjars 资源
                                "/v3/api-docs/**",              // OpenAPI 规范的 JSON 数据
                                "/swagger-resources/**",        // Swagger 资源
                                "/swagger-resources/configuration/ui",  // Swagger UI 配置
                                "/swagger-resources/configuration/security" // Swagger 安全配置
                        ).permitAll()
                        .anyRequest().authenticated()//其他的接口必须登录才能访问
        );
        //关闭防火墙
        httpSecurity.csrf(csrf -> csrf.disable());

        //自定义异常处理
        httpSecurity.exceptionHandling(ex ->
                ex.accessDeniedHandler(myAccessDeniedHandler)  //自定义的权限异常处理 作用是对于拒绝访问的用户进行拦截处理
                        .authenticationEntryPoint(myAuthenticationEntryPoint) //自定义的认证异常处理 作用是对于没有登录的用户进行拦截处理

        );

        //配置jwt过滤器
        httpSecurity.addFilterBefore(jwtTokenFilter,
                UsernamePasswordAuthenticationFilter.class);

        return httpSecurity.build();
    }
}
